package com.summerbird.mallchat.common.websocket;

import cn.hutool.core.net.url.UrlBuilder;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;

import java.net.InetSocketAddress;
import java.util.Optional;

public class MyHttpHeadersHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(final ChannelHandlerContext ctx, Object msg) {
        final HttpObject httpObject = (HttpObject) msg;

        if (httpObject instanceof HttpRequest) {
            HttpRequest req = (HttpRequest) httpObject;
            UrlBuilder urlBuilder = UrlBuilder.ofHttp(req.uri());
            // 获取请求路径中的token
            String token = Optional.ofNullable(urlBuilder.getQuery()).map(k -> k.get("token")).map(CharSequence::toString).orElse("");
            req.setUri(urlBuilder.getPath().toString());
            NettyUtil.setAttr(ctx.channel(), NettyUtil.TOKEN, token);
            // 从nginx中获取ip地址
            String ip = req.headers().get("X-Real-IP");
            if(StringUtils.isBlank(ip)){ // 没有经过nginx，则获取远端地址
                InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
                ip = address.getAddress().getHostAddress();
            }
            NettyUtil.setAttr(ctx.channel(), NettyUtil.IP, ip);
            ctx.pipeline().remove(this);
        }
        ctx.fireChannelRead(msg);
    }
}
